package com.sn.pw.service.impl;

import com.sn.pw.code.ErrorMsg;
import com.sn.pw.dao.entity.Company;
//import com.sn.pw.dao.entity.CompanyUser;
import com.sn.pw.dao.entity.User;
import com.sn.pw.dao.mapper.CompanyMapper;
import com.sn.pw.service.CompanyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sn.pw.service.UserService;
import com.sn.pw.vo.createreq.UserCreateReq;
import com.sn.pw.vo.resp.CompanyResp;
import com.sn.pw.vo.createreq.CompanyCreateReq;
import com.sn.pw.vo.resp.UserResp;
import com.sn.pw.vo.updatereq.CompanyUpdateReq;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.bean.BeanUtil;
import com.sn.pw.page.PageReq;
import com.sn.pw.page.PageResp;
import com.sn.pw.page.ConventPage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sn.pw.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.transaction.annotation.Transactional;

import static com.sn.pw.code.impl.BaseErrorCode.SERVICE_ERROR;

/**
 * <p>
 * 物流公司表 服务实现类
 * </p>
 *
 * @author mx
 * @since 2023-12-07
 */
@Service("companyService")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {
    private final UserService userService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(CompanyCreateReq param) {
        Company company = BeanUtil.toBean(param, Company.class);
        if (!super.save(company))
            throw new ServiceException(SERVICE_ERROR);
        if (!param.getUserCreateReqList().isEmpty()) {
            List<User> userList = param.getUserCreateReqList()
                    .stream()
                    .map(userCreateReq -> BeanUtil.toBean(userCreateReq, User.class).setCompanyId(company.getId()))
                    .collect(Collectors.toList());
//            List<CompanyUser>
            if (!userService.saveBatch(userList))
                throw new ServiceException(SERVICE_ERROR);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        if (!super.removeById(id))
            throw new ServiceException(SERVICE_ERROR);
        LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.<User>lambdaQuery().eq(User::getCompanyId, id);
        if (!userService.remove(lambdaQueryWrapper))
            throw new ServiceException(SERVICE_ERROR);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> ids) {
        if (!super.removeBatchByIds(ids))
            throw new ServiceException(SERVICE_ERROR);
        for (Long id : ids) {
            LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.<User>lambdaQuery().eq(User::getCompanyId, id);
            if (!userService.remove(lambdaQueryWrapper))
                throw new ServiceException(SERVICE_ERROR);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(CompanyUpdateReq param) {
        if (super.updateById(BeanUtil.toBean(param, Company.class)))
            throw new ServiceException(SERVICE_ERROR);
        if (userService.saveBatch(BeanUtil.copyToList(param.getUserCreateReqList(), User.class)))
            throw new ServiceException(SERVICE_ERROR);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CompanyResp findById(Long id) {
        Company info = super.getById(id);
        if (ObjectUtil.isEmpty(info)) {
            throw new ServiceException(SERVICE_ERROR);
        }
        CompanyResp companyResp = BeanUtil.toBean(info, CompanyResp.class);
        LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.<User>lambdaQuery().eq(User::getCompanyId, info.getCompanyId());
        companyResp.setUserRespList(BeanUtil.copyToList(userService.list(lambdaQueryWrapper), UserResp.class));
        return companyResp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CompanyResp> findList(List<Long> ids) {
        LambdaQueryWrapper<Company> lambdaQueryWrapper = Wrappers.<Company>lambdaQuery().in(Company::getId, ids);
        List<Company> list = super.list(lambdaQueryWrapper);
        List<CompanyResp> companyResp = BeanUtil.copyToList(list, CompanyResp.class);
        return companyResp
                .stream()
                .peek(companyResponse -> {
                    LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getCompanyId, companyResponse.getCompanyId());
                    companyResponse.setUserRespList(BeanUtil.copyToList(userService.list(wrapper), UserResp.class));
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageResp<CompanyResp> findPage(PageReq pageReq) {
        LambdaQueryWrapper<Company> lambdaQueryWrapper = Wrappers.lambdaQuery();
        IPage<Company> page = super.page(ConventPage.getPage(pageReq), lambdaQueryWrapper);
        PageResp<CompanyResp> pageResp = ConventPage.getPageResp(page, CompanyResp.class);
        List<CompanyResp> companyResp = pageResp.getList();
        List<CompanyResp> collect = companyResp
                .stream()
                .peek(companyResponse -> {
                    LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getCompanyId, companyResponse.getCompanyId());
                    companyResponse.setUserRespList(BeanUtil.copyToList(userService.list(wrapper), UserResp.class));
                })
                .collect(Collectors.toList());
        pageResp.setList(collect);
        return pageResp;
    }


}
